﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using ClassLibraryDatabase;

namespace ClassLibraryBaseClass
{
	/// <summary>
	/// 
	/// </summary>
	public class Movie
	{

		private int m_sID;
		private string m_sName;
		private string m_sDirector;
		private string m_sActors;
		private DateTime m_sRelease;
		private int m_nLength;
		private string m_sLanguage;
		private string m_sType;
		private string m_sNTSC;
		private decimal m_nGrade;
		private string m_sImage;
		private string m_sIntro;
		public int ID
		{ get { return m_sID; } }
		public string Name
		{ get { return m_sName; } }
		public string Director
		{ get { return m_sDirector; } }
		public string Actors
		{ get { return m_sActors; } }
		public DateTime Release
		{ get { return m_sRelease; } }
		public int Length
		{ get { return m_nLength; } }
		public string Language
		{ get { return m_sLanguage; } }
		public string Type
		{ get { return m_sType; } }
		public string NTSC
		{ get { return m_sNTSC; } }
		public decimal Grade
		{
			get { return m_nGrade; }
			set { m_nGrade = value; }
		}
		public string Image
		{
			get { return m_sImage; }
		}
		/// <summary>
		/// 
		/// </summary>
		public string Intro
		{
			get
			{
				return m_sIntro;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="sID"></param>
		/// <param name="sName"></param>
		/// <param name="sDirector"></param>
		/// <param name="sActors"></param>
		/// <param name="sRelease"></param>
		/// <param name="nLength"></param>
		/// <param name="sLanguage"></param>
		/// <param name="sType"></param>
		/// <param name="sNTSC"></param>
		/// <param name="nGrade"></param>
		/// <param name="sImage"></param>
		/// <param name="sIntro"></param>
		public Movie(int sID, string sName
			, string sDirector, string sActors
			, DateTime sRelease, int nLength
			, string sLanguage, string sType
			, string sNTSC, decimal nGrade
			, string sImage, string sIntro)
		{
			m_sID = sID;
			m_sName = sName;
			m_sDirector = sDirector;
			m_sActors = sActors;
			m_sRelease = sRelease;
			m_nLength = nLength;
			m_sLanguage = sLanguage;
			m_sType = sType;
			m_sNTSC = sNTSC;
			m_nGrade = nGrade;
			m_sImage = sImage;
			m_sIntro = sIntro;
		}
		public Movie(int sID, string sName
			, string sDirector, string sActors
			, string sRelease, int nLength
			, string sLanguage, string sType
			, string sNTSC, decimal nGrade
			, string sImage, string sIntro)
			: this(sID, sName, sDirector, sActors, GetDateTime(sRelease), nLength, sLanguage, sType, sNTSC, nGrade, sImage, sIntro)
		{
		}
		static public string GetConStr()
		{
			return DataBaseClass.GetConnectionString();
			//return "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\ibm\\Desktop\\项目\\DataBaseHelper\\DataBaseHelper\\bin\\Debug\\MOVIE.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
			//return "Server = .\\SQLExpress;AttachDbFilename = |DataDirectory|MOVIE.mdf; Database = MOVIE;Trusted_Connection = Yes;";
			//return "Data Source = .\\SQLEXPRESS;Integrated Security = true; AttachDbFilename = |DataDirectory|\\MOVIE.mdf;User Instance = true;";
			//return ConnectionString.GenerateLocalConnStringByWin("Movies");
			//return "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\ibm\\Desktop\\项目\\1\\MOVIE.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
		}
		static public DateTime GetDateTime(string Date)
		{
			int nT = 0;
			string yy = Date.Substring(0, nT = Date.IndexOf('/'));
			Date = Date.Remove(0, nT + 1);
			string mm = Date.Substring(0, nT = Date.IndexOf('/'));
			Date = Date.Remove(0, nT + 1);
			string dd = Date.Substring(0, nT = Date.IndexOf(' '));
			Date = Date.Remove(0, nT + 1);

			string hh = Date.Substring(0, nT = Date.IndexOf(':'));
			Date = Date.Remove(0, nT + 1);
			string nn = Date.Substring(0, nT = Date.IndexOf(':'));
			Date = Date.Remove(0, nT + 1);
			string ss = Date.Substring(0, Date.Length);
			return new DateTime(Convert.ToInt32(yy), Convert.ToInt32(mm), Convert.ToInt32(dd), Convert.ToInt32(hh), Convert.ToInt32(nn), Convert.ToInt32(ss));
		}
		static public bool AddItemToDatabase(int sID, string sName
			, string sDirector, string sActors
			, DateTime sRelease, int nLength
			, string sLanguage, string sType
			, string sNTSC, decimal nGrade
			, string sImage, string sIntro)
		{
			Movie movie = new Movie(sID, sName, sDirector, sActors, sRelease, nLength, sLanguage, sType, sNTSC, nGrade, sImage, sIntro);
			return movie.AddThisItemToDatabase();
		}


		/// <summary>
		/// 将自己的信息添加到数据库中
		/// </summary>
		/// <returns></returns>
		public bool AddThisItemToDatabase()
		{
			string conStr = GetConStr();

			int nT = 0;
			if (m_sIntro != null)
				++nT;
			if (m_sImage != null)
				++nT;
			nT += 9;

			string[] name = new string[nT];
			object[] value = new object[nT];

			//DataTable table = DataBaseClass.selectData(

			name[0] = "Grade";
			value[0] = m_nGrade;

			name[1] = "Name";
			value[1] = m_sName;

			name[2] = "Director";
			value[2] = m_sDirector;

			name[3] = "Actors";
			value[3] = m_sActors;

			name[4] = "Release";
			value[4] = m_sRelease;

			name[5] = "Length";
			value[5] = m_nLength;

			name[6] = "Language";
			value[6] = m_sLanguage;

			name[7] = "Type";
			value[7] = m_sType;

			name[8] = "NTSC";
			value[8] = m_sNTSC;


			if (name.Length == 11)
			{
				name[9] = "Image";
				value[9] = m_sImage;

				name[10] = "Intro";
				value[10] = m_sIntro;
			}
			else if (m_sImage != null && m_sImage != "")
			{
				name[9] = "Image";
				value[9] = m_sImage;
			}
			else if (m_sIntro != null && m_sIntro != "")
			{
				name[9] = "Intro";
				value[9] = m_sIntro;
			}

			try
			{
				bool b = DataBaseClass.insertData(name, value, "Movies", conStr);
				m_sID = Movie.GetMaxID();
				return b;
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		/// <summary>
		/// 将自己的信息从数据库中删除
		/// </summary>
		/// <returns></returns>
		public bool[] DeleteItselfFromDatabase()
		{
			return DeleteItemFromDatabase(this.m_sID);
		}
		/// <summary>
		/// 获得与自己电影相关的所有评论
		/// </summary>
		/// <returns></returns>
		public DataTable GetCommentByMovie()
		{
			try
			{
				return DataBaseClass.selectData("SELECT * FROM M_Comment WHERE MovieID=" + this.m_sID.ToString(), GetConStr());
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
		}
		/// <summary>
		/// 获得与自己电影相关的所有场次
		/// </summary>
		/// <returns></returns>
		public DataTable GetSessionByMovie()
		{
			try
			{
				return DataBaseClass.selectData("SELECT * FROM Session WHERE Session.MovieID=" + this.m_sID.ToString(), GetConStr());
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
		}
		/// <summary>
		/// 获得播放自己电影的所有剧院
		/// </summary>
		/// <returns></returns>
		public DataTable GetTheatreByMovie()
		{
			try
			{
				return DataBaseClass.selectData("SELECT * FROM Theater WHERE ID IN (SELECT DISTINCT TheaterID FROM Session WHERE MovieID=" + this.m_sID.ToString() + ")", GetConStr());
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
		}
		/// <summary>
		/// 更新自己在数据库中的记录
		/// </summary>
		/// <returns></returns>
		public bool Update()
		{
			Movie movie = Movie.GetMovieByID(m_sID.ToString());
			string sql = "UPDATE Movies SET ";
			if (m_sName != movie.m_sName)
				sql += " Name=" + m_sName + ",";
			if (m_sDirector != movie.m_sDirector)
				sql += "Director=" + m_sDirector + ",";
			if (m_sActors != movie.m_sActors)
				sql += "Actors=" + m_sActors + ",";
			if (m_sRelease != movie.m_sRelease)
				sql += "Release=" + m_sRelease.ToString() + ",";
			if (m_nLength != movie.m_nLength)
				sql += "Length=" + m_nLength.ToString() + ",";
			if (m_sLanguage != movie.m_sLanguage)
				sql += "Language=" + m_sLanguage + ",";
			if (m_sType != movie.m_sType)
				sql += "Type=" + m_sType + ",";
			if (m_sNTSC != movie.m_sNTSC)
				sql += "NTSC=" + m_sNTSC + ",";
			if (m_nGrade != movie.m_nGrade)
				sql += "Grade=" + m_nGrade + ",";
			if (m_sImage != movie.m_sImage)
				sql += "Image=" + m_sImage + ",";
			if (m_sIntro != movie.m_sIntro)
				sql += "Intro=" + m_sIntro;
			if (sql.EndsWith(","))
				sql = sql.Remove(sql.Length - 1, 1);
			else if (sql.EndsWith("SET "))
				return false;
			sql += " WHERE ID=" + m_sID.ToString();
			try
			{
				return DataBaseClass.Update(sql, GetConStr());
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		/// <summary>
		/// 添加自己在数据库中的新评分
		/// </summary>
		/// <param name="dNew"></param>
		/// <returns></returns>
		public bool AddNewGrade(decimal dNew)
		{
			this.m_nGrade = (this.m_nGrade + dNew) / 2;
			return Update();
		}


		/// <summary>
		/// 获得当前最大的ID号
		/// </summary>
		/// <returns></returns>
		static public int GetMaxID()
		{
			try
			{
				DataTable table = DataBaseClass.selectData("SELECT MAX(ID) AS ID FROM Movies", GetConStr());
				string s = table.Rows[0]["ID"].ToString();
				return Convert.ToInt32(table.Rows[0]["ID"].ToString());
			}
			catch (IndexOutOfRangeException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return 0;
			}
			catch (Exception e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return -1;
			}

		}
		/// <summary>
		/// 通过ID获得一个电影对象
		/// </summary>
		/// <param name="id">电影编号</param>
		/// <returns></returns>
		static public Movie GetMovieByID(string id)
		{
			string sql = "SELECT * FROM Movies WHERE ID=" + id + "";
			try
			{
				DataTable table = DataBaseClass.selectData(sql, GetConStr());
				if (table.Rows.Count == 0)
					return null;
				return GetMovieByDataTable(table.Rows[0]);
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			//return new Movie(Convert.ToInt32(table.Rows[0]["ID"].ToString())
			//    , table.Rows[0]["Name"].ToString()
			//    , table.Rows[0]["Director"].ToString()
			//    , table.Rows[0]["Actors"].ToString()
			//    , GetDateTime(table.Rows[0]["Release"].ToString())
			//    , Convert.ToInt32(table.Rows[0]["Length"])
			//    , table.Rows[0]["Language"].ToString()
			//    , table.Rows[0]["Type"].ToString()
			//    , table.Rows[0]["NTSC"].ToString()
			//    , Convert.ToInt32(table.Rows[0]["Grade"])
			//    , table.Rows[0]["Image"] as string
			//    , table.Rows[0]["Intro"] as string
			//    );
		}
		/// <summary>
		/// 通过电影名获得一系列电影的列表，他们的电影名与此相似
		/// </summary>
		/// <param name="name">电影名</param>
		/// <returns></returns>
		static public DataTable GetMovieByName(string name)
		{
			string sql = "SELECT * FROM Movies WHERE NAME LIKE '%" + name + "%'";
			try
			{
				DataTable table = DataBaseClass.selectData(sql, GetConStr());
				return table;
			}
			catch (SqlException e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			catch (Exception e)
			{
				System.Console.Write("Movie类：");
				System.Console.WriteLine(e.Message);
				return null;
			}
			//if (table.Rows.Count == 0)
			//    return null; 
			//return table;
			//return new Movie(Convert.ToInt32(table.Rows[0]["ID"].ToString())
			//    , table.Rows[0]["Name"].ToString()
			//    , table.Rows[0]["Director"].ToString()
			//    , table.Rows[0]["Actors"].ToString()
			//    , GetDateTime(table.Rows[0]["Release"].ToString())
			//    , Convert.ToInt32(table.Rows[0]["Length"])
			//    , table.Rows[0]["Language"].ToString()
			//    , table.Rows[0]["Type"].ToString()
			//    , table.Rows[0]["NTSC"].ToString()
			//    , Convert.ToInt32(table.Rows[0]["Grade"])
			//    , table.Rows[0]["Image"] as string
			//    , table.Rows[0]["Intro"] as string
			//    );
		}
		/// <summary>
		/// 将存储Movie信息的DataTable对象转换为List<Movie>对象
		/// </summary>
		/// <param name="table">存储电影信息的DataTable对象</param>
		/// <returns></returns>
		static public List<Movie> GetMovieListByDataTable(DataTable table)
		{
			List<Movie> list = new List<Movie>();
			for (int i = 0; i < table.Rows.Count; ++i)
			{
				list.Add(GetMovieByDataTable(table.Rows[i]));
				//list.Add(new Movie(Convert.ToInt32(table.Rows[i]["ID"].ToString())
				//, table.Rows[i]["Name"].ToString()
				//, table.Rows[i]["Director"].ToString()
				//, table.Rows[i]["Actors"].ToString()
				//, GetDateTime(table.Rows[i]["Release"].ToString())
				//, Convert.ToInt32(table.Rows[i]["Length"])
				//, table.Rows[i]["Language"].ToString()
				//, table.Rows[i]["Type"].ToString()
				//, table.Rows[i]["NTSC"].ToString()
				//, Convert.ToInt32(table.Rows[i]["Grade"])
				//, table.Rows[i]["Image"] as string
				//, table.Rows[i]["Intro"] as string
				//));
			}
			return list;
		}
		/// <summary>
		/// 通过一个DataRow对象获得一个Movie对象
		/// </summary>
		/// <param name="collection">DataRow对象</param>
		/// <returns></returns>
		static public Movie GetMovieByDataTable(DataRow collection)
		{
			return new Movie(Convert.ToInt32(collection["ID"].ToString())
				, collection["Name"].ToString()
				, collection["Director"].ToString()
				, collection["Actors"].ToString()
				, (DateTime)collection["Release"]
				, Convert.ToInt32(collection["Length"])
				, collection["Language"].ToString()
				, collection["Type"].ToString()
				, collection["NTSC"].ToString()
				, Convert.ToInt32(collection["Grade"])
				, collection["Image"] as string
				, collection["Intro"] as string
				);
		}
		/// <summary>
		/// 通过电影ID删除数据库中的信息
		/// </summary>
		/// <param name="nID">电影的ID</param>
		/// <returns></returns>
		static public bool[] DeleteItemFromDatabase(int nID)
		{
			bool[] bT = new bool[4];
			bool[] bF = DeleteRelationship(nID);
			bT[1] = bF[0];
			bT[2] = bF[1];
			bT[3] = bF[2];
			bT[0] = DataBaseClass.deleteData("ID", nID, "Movies", GetConStr());


			return bT;
		}
		/// <summary>
		/// 删除与此电影信息相关的所有信息，在"Session"和"M_Comment"中
		/// </summary>
		/// <param name="nID"></param>
		/// <returns></returns>
		static public bool[] DeleteRelationship(int nID)
		{
			bool[] bT = { false, false, false };
			List<MComment> mList = MComment.GetListFromDataTable(DataBaseClass.selectData("SELECT * FROM M_Comment WHERE MovieID=" + nID, GetConStr()));
			try
			{
				foreach (MComment comment in mList)
				{
					comment.DelM_Comment();
				}
				bT[0] = true;
			}
			catch (Exception e)
			{
				bT[0] = false;
			}
			List<SessionInfo> sList = SessionInfo.GetListByDataTable(DataBaseClass.selectData("SELECT * FROM Session WHERE MovieID=" + nID, GetConStr()));
			try
			{
				foreach (SessionInfo info in sList)
				{
					info.DeleteSelfInfo();
				}
				bT[1] = true;
			}
			catch (Exception e)
			{
				bT[1] = false;
			}
			List<Favorites> fList = Favorites.GetListOfFavoritesByDatatable(DataBaseClass.selectData("SELECT * FROM Favourites WHERE MovieID=" + nID, GetConStr()));
			try
			{
				foreach (Favorites favorites in fList)
				{
					favorites.DeleteFavoriteMovie();
				}
				bT[2] = true;
			}
			catch (Exception e)
			{
				bT[2] = false;
			}
			return bT;
		}
	}

	public class Test3
	{
		public static void Test()
		{
			Movie movie = new Movie(-1, "asdfar", "asdf", "asdf", DateTime.Today, 120, "asdf", "asdf", "a3wr", 5.5M, null, "AEASDF");
			movie.AddThisItemToDatabase();
			if (movie.ID != Movie.GetMaxID())
				System.Console.WriteLine("ID出错");
			movie = Movie.GetMovieByID(Movie.GetMaxID().ToString());
			if (movie == null)
				System.Console.WriteLine("Movie获取出错");
			movie.DeleteItselfFromDatabase();
			movie = Movie.GetMovieByID(movie.ID.ToString());
			if (movie != null)
				System.Console.WriteLine("Movie删除出错");
		}
	}
}